package cn.wolfcode.car.shiro;

import cn.wolfcode.car.domain.Employee;
import cn.wolfcode.car.domain.Role;
import cn.wolfcode.car.service.IEmployeeService;
import cn.wolfcode.car.service.IPermissionService;
import cn.wolfcode.car.service.IRoleService;
import cn.wolfcode.car.util.UserContextUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.List;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private IEmployeeService employeeService;

    @Autowired
    @Lazy
    private IRoleService roleService;

    @Autowired
    @Lazy
    private IPermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        UserContextUtil.setCurrentEmployee(employee);
        if(employee.isAdmin()){
            List<Role> roles = roleService.listAll();
            if(roles != null){
                for (Role role : roles) {
                    info.addRole(role.getSn());
                }
            }
            info.addStringPermission("*:*");
        }else{
            List<String> sns = roleService.queryBySn(employee.getId());
            info.addRoles(sns);
            List<String> expressions = permissionService.queryByExpression(employee.getId());
            info.addStringPermissions(expressions);
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        //获取用户信息
        Employee employee = employeeService.queryByUsername(username);
        if(employee != null){
            return new SimpleAuthenticationInfo(employee,
                    employee.getPassword(),
                    this.getName());
        }
        return null;
    }
}
